import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:ls_work/net/post_request.dart';

import '../../net/response/devices/equipment_task_list_data.dart';

class DeviceRepairSubmitViewModel extends BaseViewModel {
  final String? id;
  final String? content;

  DeviceRepairSubmitViewModel(BuildContext context, {this.content, this.id})
      : super(context);

  static const List<String> format = [
    yyyy,
    '-',
    mm,
    '-',
    dd,
    ' ',
    HH,
    ':',
    nn,
    ':',
    ss
  ];

  ///执行时间
  var _finishDateTime = DateTime.now();
  var finishTime = DateTime.now().toDateStr(format);

  var repairResultName = "";
  var repairResultId = "";
  var inputContent = '';

  var repairResultList = [
    PickerDataWithIdModel(pickName: '正常维保',pickId: '0'),
    PickerDataWithIdModel(pickName: '维修',pickId: '1')
  ];

  EquipmentTaskListData? taskData;

  void selectFinishTime() {
    DatePicker.showDateTimePicker(context, currentTime: _finishDateTime,
        onConfirm: (date) {
      _finishDateTime = date!;
      finishTime = date!.toDateStr(format);
      notifyListeners();
    });
  }

  void selectRepairResult() {
    DataPickerView(context, repairResultList, onSubmitListener: (p1, p2, p3) {
      var item = repairResultList[p1];
      repairResultName = item.pickName??"";
      repairResultId = item.pickId!;
      notifyListeners();
    }).show();
  }

  Future<void> getTask() async {
    showLoadingState();
    try {
      var data = await PostRequest.getEquipmentTask(content, id);
      if ('0' == data['code'].toString()) {
        if (data['data'] != null && (data['data'] as List).isNotEmpty) {
          taskData = EquipmentTaskListData.fromJson((data['data'] as List)[0]);
          notifyListeners();
          showContent();
        } else {
          showEmptyState();
        }
      } else {
        showErrorState(data['msg']);
      }
    } catch (e) {
      showErrorState(NetErrorUtils.getNetError(e));
    }
  }

  Future<void> submitRepair() async {
    if(repairResultId.isNullOrEmpty()){
      showToast('请选择维保结果');
      return;
    }
    if(inputContent.isNullOrEmpty()){
      showToast('请输入维保内容');
      return;
    }
    showLoadingDialog(msg:'提交中...');
    try{
      var data = await PostRequest.submitEquipmentTask(taskData?.id.toString()??"", inputContent, finishTime, repairResultId);
      if('0'==data['code'].toString()){
        showToast('提交成功');
        finish();
        // sendMessage(SendMessageEvent(msgCode))
      }else{
        showToast(data['msg']);
      }
    }catch(e){
      hideDialog();
      showToast(NetErrorUtils.getNetError(e));
    }
  }

  @override
  void onCreated() {
    super.onCreated();
    getTask();
  }
}
